package cn.nfwx.tv.controller;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import cn.nfwx.tv.R;
import cn.nfwx.tv.adapter.LookBackDateAdapter2;
import cn.nfwx.tv.adapter.LookBackProgramAdapter;
import cn.nfwx.tv.base.BaseDialogFragment;
import cn.nfwx.tv.callback.ResponseListener;
import cn.nfwx.tv.db.DownProgramModel;
import cn.nfwx.tv.fragment.callback.ActionCallback;
import cn.nfwx.tv.helper.AccountHelper;
import cn.nfwx.tv.helper.NetworkHelper;
import cn.nfwx.tv.helper.ValueCallback;
import cn.nfwx.tv.manager.AppointmentManager;
import cn.nfwx.tv.model.DateProgram;
import cn.nfwx.tv.model.Result;
import cn.nfwx.tv.model.TVProgramModel;
import cn.nfwx.tv.model.TvProgram;
import cn.nfwx.tv.util.DensityUtil;
import cn.nfwx.tv.util.RecyclerViewUtil;
import cn.nfwx.tv.util.SharePrefUtil;
import cn.nfwx.tv.util.TimeUtil;
import cn.nfwx.tv.util.ToastUtil;
import cn.nfwx.tv.widget.AutoAdjustRecylerView;

/**
 * 回看弹出框
 * Created by zhouzechao on 2017/11/17.
 */

public class TVProgramsViewController extends BaseDialogFragment implements View.OnClickListener, BaseQuickAdapter.OnItemClickListener {
    //(TVProgramModel的status) 1、回看、下载 2、正在直播 3、预定 4、下载中 5、下载完成 6、已预约 7、正在处理
    public static final int PROGRAM_STATUS_LOOKBACK = 1;
    public static final int PROGRAM_STATUS_LIVING = 2;
    public static final int PROGRAM_STATUS_SUBCRIPTION = 3;
    public static final int PROGRAM_STATUS_DOWNING = 4;
    public static final int PROGRAM_STATUS_DOWNED = 5;
    public static final int PROGRAM_STATUS_SUBCRIPTIONED = 6;
    public static final int PROGRAM_STATUS_PROCESS = 7;

    private static final int STATS_P2P = 1;
    private static final int STATS_IJK = 2;

    private static final String KEY_PROGRAMS = "key_programs";
    private static final String KEY_TYPE = "key_type";
    private static final String KEY_PROGRAM_NAME = "key_program_name";
    private static final String KEY_PROGRAM = "key_program";
    private static final String KEY_ISCALLBACK = "key_iscallback";
    private static final String KEY_GID = "key_gid";
    private static final String KEY_STATS = "key_stats";

    private static final String KEY_DATE_PROGRAM = "key_date_program";

    private TextView tvprogram_cancle_btn;
    private AutoAdjustRecylerView rv_left, rv_right;
    private LookBackDateAdapter2 lookBackDateAdapter;
    private LookBackProgramAdapter lookBackProgramAdapter;

    private View mview;
    private View tv_lookback_nodata;

    private List<DateProgram> mDatePrograms;
    private int dateSelected; // 正在播放 对应的日子位置
    private int programSelected; // 正在播放 节目的位置
    private TvProgram program;
    private String gid;

    private ActionCallback mActionCallback;
    public static final String ACTION_PROGRAM_CLICK = "ACTION_PROGRAM_CLICK";
    public static final String ACTION_PROGRAM_ITEMCLICK = "ACTION_PROGRAM_ITEMCLICK";


    public static TVProgramsViewController newInstance() {
        TVProgramsViewController fragment = new TVProgramsViewController();
        return fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActionCallback = ActionCallback.NONE;
        if (activity instanceof ActionCallback) {
            mActionCallback = (ActionCallback) activity;
        }
    }

    /**
     * 是否填满整个屏幕
     */
    protected boolean isMatchParent() {
        return true;
    }

    protected boolean isOutsideTouchable() {
        return true;
    }

    //是否透明背景
    protected boolean isTranslucentBackground() {
        return true;
    }

    protected boolean isTranslucentStatus() {
        return false;
    }

    protected int getGravity() {
        return Gravity.BOTTOM;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tvprogram_lookback;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvprogram_cancle_btn = findView(R.id.tvprogram_cancle_btn);
        findView(R.id.content).setOnClickListener(this);
        rv_left = findView(R.id.rv_left);
        HorizontalDividerItemDecoration itemDecoration = new HorizontalDividerItemDecoration.Builder(getContext())
                .color(Color.TRANSPARENT)
                .size(62)
                .build();

        rv_left.addItemDecoration(itemDecoration);

        rv_right = findView(R.id.rv_right);
        rv_right.addItemDecoration(itemDecoration);

        lookBackDateAdapter = new LookBackDateAdapter2();
        RecyclerViewUtil.setLinearLayoutManagerWithoutDivder(getContext(), rv_left);
        rv_left.setAdapter(lookBackDateAdapter);

        lookBackProgramAdapter = new LookBackProgramAdapter();
        RecyclerViewUtil.setLinearLayoutManagerWithoutDivder(getContext(), rv_right);
        rv_right.setAdapter(lookBackProgramAdapter);

        /**
         * 监听生命周期
         */
        getLifecycle().addObserver(lookBackDateAdapter);
        getLifecycle().addObserver(lookBackProgramAdapter);

        mview = findView(R.id.view);
        tv_lookback_nodata = findView(R.id.tv_lookback_nodata);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 获取Bundle的数据队列
        Bundle bundle = getArguments();

        int stats = bundle.getInt(KEY_STATS);
        if (stats == STATS_IJK) {
            List<TvProgram> tvPrograms = bundle.getParcelableArrayList(KEY_PROGRAMS);
            program = bundle.getParcelable(KEY_PROGRAM); // 回放对应的节目
            boolean isLive = bundle.getBoolean(KEY_TYPE); // 直播还是回放
            List<String> dates = new ArrayList<>();
//            List<String> d = bundle.getStringArrayList(KEY_DATE);
//            dates.addAll(d);
            List<DateProgram> datePrograms = bundle.getParcelableArrayList(KEY_DATE_PROGRAM);
            mDatePrograms = new ArrayList<>(datePrograms);
            gid = bundle.getString(KEY_GID);

            for (DateProgram dateProgram : mDatePrograms) {
                dates.add(dateProgram.getDate());
            }

            Collections.sort(dates);

            tv_lookback_nodata.setVisibility((tvPrograms == null || tvPrograms.isEmpty()) ? View.VISIBLE : View.GONE);
            mview.setVisibility((tvPrograms == null || tvPrograms.isEmpty()) ? View.GONE : View.VISIBLE);
            rv_left.setVisibility((tvPrograms == null || tvPrograms.isEmpty()) ? View.GONE : View.VISIBLE);
            rv_right.setVisibility((tvPrograms == null || tvPrograms.isEmpty()) ? View.GONE : View.VISIBLE);

            if (program == null) {
                String date = TimeUtil.getFormatYYMMddTime(TimeUtil.getTime());
                if (isLive) {
                    dateSelected = dates.indexOf(date);
                }
            } else {
                if (!isLive) {
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    try {
                        if (!TextUtils.isEmpty(program.getTime())) {
                            Date date = dateFormat.parse(program.getTime());
                            String dateStr = TimeUtil.getFormatYYMMddTime(date.getTime() / 1000L);
                            dateSelected = dates.indexOf(dateStr);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }

            if (dateSelected == -1) {
                dateSelected = 0;
            }
            lookBackDateAdapter.setSelect(dateSelected);
            lookBackDateAdapter.setNewData(dates);

            if (lookBackProgramAdapter != null && program != null) {
                lookBackProgramAdapter.setProgram(program.getUrl());
            }

            if (datePrograms.isEmpty() || dates.isEmpty()) {
                return;
            }

            // 放入节目数据
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String d = dates.get(dateSelected);
            List<TvProgram> programList = null;
            for (DateProgram dateProgram : datePrograms) {
                if (dateProgram.getDate().equals(d)) {
                    programList = dateProgram.getTvPrograms();
                    break;
                }
            }
            if (programList != null) {
                for (int i = 0; i < programList.size(); i++) {
                    TvProgram tvProgram = programList.get(i);
                    if (program == null) {
                        Date date = null;
                        try {
                            date = dateFormat.parse(tvProgram.getTime());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        assert date != null;
                        if (date.getTime() <= System.currentTimeMillis()) {
                            if ((i + 1) < programList.size()) {
                                Object object1 = programList.get(i + 1);
                                TvProgram tvProgram1 = (TvProgram) object1;
                                Date date1 = null;
                                try {
                                    date1 = dateFormat.parse(tvProgram1.getTime());
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                assert date1 != null;
                                if (date1.getTime() > System.currentTimeMillis()) {
                                    programSelected = i;
                                }
                            } else {
                                String timeProgram = TimeUtil.getFormatYYMMddTime(date);
                                String time = TimeUtil.getFormatYYMMddTime(System.currentTimeMillis());
                                if (timeProgram.equals(time)) {
                                    programSelected = i;
                                }
                                if (date.getTime() < System.currentTimeMillis()) {
                                    String t1 = TimeUtil.getFormat2Time(date.getTime());
                                    String t2 = TimeUtil.getFormat2Time(System.currentTimeMillis());
                                    if (TextUtils.isEmpty(tvProgram.getUrl()) && t1.equals(t2)) {
                                        programSelected = i;
                                    }
                                } else if (date.getTime() == System.currentTimeMillis()) {
                                    programSelected = i;
                                }
                            }
                        }
                    } else {
                        if (!TextUtils.isEmpty(tvProgram.getUrl()) && !TextUtils.isEmpty(program.getUrl()) && program.getUrl().equals(tvProgram.getUrl())) {
                            programSelected = i;
                            break;
                        }
                    }
                }
            }
            if (lookBackProgramAdapter != null) {
                lookBackProgramAdapter.setNewData(programList);
            }
        }

        lookBackDateAdapter.setOnItemClickListener(this);
        lookBackProgramAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                Object model = adapter.getData().get(position);
                if (model instanceof TvProgram) {
                    TvProgram tvProgram = (TvProgram) model;
                    switch (view.getId()) {
                        case R.id.lookback_program_download_btn:
                            if (!AccountHelper.getInstance().isLogin(getContext())) {
                                ToastUtil.show(getContext(), "用户未登录", Toast.LENGTH_LONG);
                                return;
                            }
                            if (!TextUtils.isEmpty(tvProgram.getUrl())) {
                                // 回看更新下载ui
                                if (!NetworkHelper.getInstance().hasConnection(getContext())) {
                                    ToastUtil.show(getContext(), R.string.nointernet, Toast.LENGTH_LONG);
                                    return;
                                }
                                if (NetworkHelper.getInstance().isConnection4g(getContext())
                                        && !SharePrefUtil.getDownloadChoose(getContext())) {
                                    ToastUtil.show(getContext(), R.string.download_4g, Toast.LENGTH_LONG);
                                    return;
                                }
                                DownloadM3u8Controller.getInstance().download(getContext(), tvProgram, TVProgramsViewController.this.<Integer>bindToLifecycle(), new ValueCallback<Integer>() {
                                    @Override
                                    public void onReceiveValue(final Integer value) {
                                        if (value == DownProgramModel.STATS_FAIL) {
                                            ToastUtil.show(getContext(), "下载失败");
                                        } else if (value == DownProgramModel.STATS_DOWNLOADED) {
                                            ToastUtil.show(getContext(), "已正在下载");
                                        } else {
                                            downNotifyData(position);
                                            ToastUtil.show(getContext(), "正在下载");
                                        }
                                    }
                                });
                            } else {
                                if (tvProgram.getType() == 2) {
                                    AppointmentManager.requestAddAppointment(getContext(), gid, new ResponseListener<String>() {
                                        @Override
                                        public void onResponse(String requestTag, String response) {
                                            Result result = JSON.parseObject(response, new TypeReference<Result>() {
                                            }.getType());
                                            if (Result.RESULT_SUCCESS.equals(result.getMessage())) {
                                                AccountHelper.getInstance().refreshDaoAppoint(getContext(), TVProgramsViewController.this.<Boolean>bindToLifecycle(), new ValueCallback<Boolean>() {
                                                    @Override
                                                    public void onReceiveValue(Boolean value) {
                                                        ToastUtil.show(getContext(), "预约成功", Toast.LENGTH_LONG);
                                                        subscriptionNotifyData(position);
                                                    }
                                                });
                                            }
                                        }

                                        @Override
                                        public void onError(String requestTag, Throwable t) {

                                        }

                                        @Override
                                        public void onFinish() {

                                        }
                                    }, tvProgram.getProgram_id());
                                }
                            }
                            break;
                        default:
                            if (mActionCallback != null) {
                                Bundle bundle = new Bundle();
                                bundle.putParcelable("data", tvProgram);
                                mActionCallback.callbackByfragment(ACTION_PROGRAM_ITEMCLICK, bundle);
                                dismissAllowingStateLoss();
                            }
                            break;
                    }
                }
            }
        });

        tvprogram_cancle_btn.setOnClickListener(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        release();
        mActionCallback = ActionCallback.NONE;
    }


    @Override
    public void onResume() {
        super.onResume();
        int top = DensityUtil.getHeight(getContext()) / 2 - DensityUtil.dip2px(getContext(), 15);
        ((LinearLayoutManager) rv_left.getLayoutManager()).scrollToPositionWithOffset(dateSelected, top);
        ((LinearLayoutManager) rv_right.getLayoutManager()).scrollToPositionWithOffset(programSelected, top);
    }


    @Override
    public void onDismiss(DialogInterface dialog) {
        boolean _isCallBack = getArguments().getBoolean(KEY_ISCALLBACK, true);
        if (mActionCallback != null && _isCallBack) {
            Bundle bundle = new Bundle();
            bundle.putInt("id", tvprogram_cancle_btn.getId());
            mActionCallback.callbackByfragment(ACTION_PROGRAM_CLICK, bundle);
        }
        super.onDismiss(dialog);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.content:
            case R.id.tvprogram_cancle_btn:
                dismiss();
                break;
        }
    }

    /**
     * 关闭按钮
     *
     * @param mPositiveListener
     */
//    public void setPositiveListener(View.OnClickListener mPositiveListener) {
//        this.mPositiveListener = mPositiveListener;
//    }

    /**
     * 是指节目选择的监听
     *
     * @param listener
     */
//    public void setProgramItemListener(BaseQuickAdapter.OnItemChildClickListener listener) {
//        mItemClickListener = listener;
//    }

    /**
     * 设置数据，放到容器里并从onViewCreated之后再拿出来
     * 针对直播的队列进行对应的部分查找
     *
     * @param data
     * @param name
     */
    public void setData(List<TVProgramModel> data, String name, boolean isLive) {
        setData(data, name, isLive, null);
    }


    /**
     * p2p针对播放视频部分
     *
     * @param data
     * @param name
     * @param model
     */
    public void setData(List<TVProgramModel> data, String name, boolean isLive, TVProgramModel model) {
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(KEY_PROGRAMS, (ArrayList<? extends Parcelable>) data);
        bundle.putString(KEY_PROGRAM_NAME, name);
        bundle.putBoolean(KEY_TYPE, isLive);
        bundle.putParcelable(KEY_PROGRAM, model);
        bundle.putInt(KEY_STATS, STATS_P2P);
        this.setArguments(bundle);
    }

    /**
     * ijk针对播放回看部分
     *
     * @param tvPrograms
     * @param name
     * @param gid
     * @param isLive
     * @param mTvProgram
     */
    public void setData(List<DateProgram> dateProgram, List<TvProgram> tvPrograms, String name, String gid, boolean isLive, TvProgram mTvProgram) {
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(KEY_DATE_PROGRAM, (ArrayList<? extends Parcelable>) dateProgram);
        bundle.putParcelableArrayList(KEY_PROGRAMS, (ArrayList<? extends Parcelable>) tvPrograms);
        bundle.putString(KEY_PROGRAM_NAME, name);
        bundle.putString(KEY_GID, gid);
        bundle.putBoolean(KEY_TYPE, isLive);
        bundle.putParcelable(KEY_PROGRAM, mTvProgram);
        bundle.putInt(KEY_STATS, STATS_IJK);
        this.setArguments(bundle);
    }


    /**
     * 销毁，防止内存溢出,有请求销毁请求
     */
    public void release() {
        if (lookBackProgramAdapter != null) {
            lookBackProgramAdapter.setOnItemClickListener(null);
        }
        if (lookBackDateAdapter != null) {
            lookBackDateAdapter.setOnItemChildClickListener(null);
        }
    }

    /**
     * 手动操作下载后更新ui
     *
     * @param position
     */
    public void downNotifyData(int position) {
        lookBackProgramAdapter.notifyItemChanged(position);
    }

    /**
     * 预约
     *
     * @param position
     */
    public void subscriptionNotifyData(int position) {
        TvProgram tvProgram = lookBackProgramAdapter.getData().get(position);
        tvProgram.setHasAppoint(true);
        lookBackProgramAdapter.notifyItemChanged(position);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        lookBackDateAdapter.setSelect(position);
        lookBackDateAdapter.notifyDataSetChanged();
        rv_left.checkVerticalAutoAdjust(position);
        if (program == null) {
            String date = TimeUtil.getFormatYYMMddTime(TimeUtil.getTime());
            String date1 = lookBackDateAdapter.getData().get(position);
            if (date.equals(date1)) {
                ((LinearLayoutManager) rv_right.getLayoutManager()).scrollToPositionWithOffset(programSelected, (int) (rv_right.getHeight() / 2 - getResources().getDimension(R.dimen.dp20) / 2));
            } else {
                rv_right.scrollToPosition(0);
            }
        }
        String d = lookBackDateAdapter.getData().get(position);
        for (DateProgram dateProgram : mDatePrograms) {
            if (dateProgram.getDate().equals(d)) {
                lookBackProgramAdapter.setNewData(dateProgram.getTvPrograms());
                break;
            }
        }
    }
}
